package config

import (
	"os"

	"aiserver/pkg/models"
	"fmt"

	"gitee.com/wujianqiang/golibs/pkg/factory"
	"gopkg.in/yaml.v3"
)

func PrepareServer(c string) error {
	if Appconfig != nil {
		return nil
	}

	err := readYaml(c)
	if err != nil {
		fmt.Println(err)
		return err
	}

	// set mysql factory connection
	db, err := factory.NewDbConnection(&Appconfig.Mysql)
	if err != nil {
		return err
	}
	Appconfig.DB = db
	db.AutoMigrate(models.MODELS...)
	// set redis connection
	rds, err := factory.NewRedisConnection(&Appconfig.Redis)
	if err != nil {
		return err
	}
	Appconfig.RDS = rds

	sbc, err := Appconfig.SpiceConfig.NewClient()
	if err != nil {
		return err
	}
	Appconfig.SPDB = sbc

	return nil
}

func readYaml(filename string) error {
	var appConfig AppConfig
	yamlFile, err := os.ReadFile(filename)

	if err != nil {
		return err
	}

	err = yaml.Unmarshal(yamlFile, &appConfig)
	if err != nil {
		return err
	}
	SetAppConfig(&appConfig)

	return nil
}
